package com.example.food.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.food.adapter.FoolListAdapter;
import com.example.food.adapter.ShowAddressAdapter;
import com.example.food.bean.AddressList;
import com.example.food.bean.AlacarteBean;
import com.example.food.bean.CerateOrder;
import com.example.food.bean.FoodData;
import com.example.home.R;
import com.example.home.tool.GeneralClass;
import com.example.home.tool.OKHttpTool;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class ProductsettlementActivity extends AppCompatActivity {
    private AddressList.DataBean addressData;
    private ImageView back;
    private FrameLayout frame;
    private TextView delivery;
    private RelativeLayout readdressDetail;
    private TextView address;
    private TextView name;
    private TextView pay;
    private TextView phone;
    private RecyclerView refoodlist;
    private RelativeLayout submitorder;
    private TextView tv_money;
    List<AlacarteBean.DataBean> list;
    private static final int REQUEST_CODE_DELIVERY = 1;
    private RecyclerView deliverygoodslist;
    public BottomSheetDialog bottomSheetDialog;
    private String money;
    private Gson gson;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_productsettlement);
        initView();

        varietyList();
        createOrder();
    }

    private CerateOrder createOrderObject() {
        List<FoodData> foodData = new ArrayList<>();
        String sellerId = String.valueOf(list.get(0).getSellerId());
        for (AlacarteBean.DataBean data : list){
            foodData.add(new FoodData(data.getId(),data.getCounter()));
        }
        CerateOrder cerateOrder = new CerateOrder();
        cerateOrder.setAddressDetail(addressData.getAddressDetail());
        cerateOrder.setAmount(Double.parseDouble(money));
        Log.v("xhf","money="+money);
        cerateOrder.setLabel(addressData.getLabel());
        cerateOrder.setName(addressData.getName());
        cerateOrder.setPhone(addressData.getPhone());
        cerateOrder.setSellerId(sellerId);
        cerateOrder.setOrderItemList(foodData);
        return cerateOrder;
    }


    private void createOrder() {
        pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (createOrderObject() != null) {
                        CerateOrder cerateOrder = createOrderObject();
                        String orderData = gson.toJson(cerateOrder);
                        PayOrder(orderData);
                    } else {
                        Toast.makeText(ProductsettlementActivity.this, "请填写信息完整", Toast.LENGTH_SHORT).show();
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    private void PayOrder(String orderData) {
        OKHttpTool.doNetRequest("prod-api/api/takeout/order/create",
                OKHttpTool.POST,
                GeneralClass.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        GeneralClass generalClass = (GeneralClass) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (generalClass.getCode() == 200){
                                    Log.v("xhf", generalClass.getOrderNo());
                                    Intent intent = new Intent(ProductsettlementActivity.this, PayOrderActivity.class);
                                    intent.putExtra("OrderNo", generalClass.getOrderNo());
                                    intent.putExtra("orderMoney", money);
                                    startActivity(intent);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                },orderData);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_DELIVERY && resultCode == RESULT_CANCELED) {
            bottomSheetDialog.dismiss();
        } else if (requestCode == REQUEST_CODE_DELIVERY && resultCode == RESULT_OK) {
            // 处理返回的数据
            String result = data.getStringExtra("keyName");
            // 刷新底部弹窗的数据
            refreshBottomSheetData(result);
        }

    }

    private void refreshBottomSheetData(String result) {
        sendAddressList(deliverygoodslist);
    }


    private void varietyList() {
        refoodlist.setAdapter(new FoolListAdapter(ProductsettlementActivity.this,list));
        refoodlist.setLayoutManager(new LinearLayoutManager(ProductsettlementActivity.this));
    }



    private void showAddress(String result) {
        findViewById(R.id.delivery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog = new BottomSheetDialog(ProductsettlementActivity.this);
                View bottomSheetView = LayoutInflater.from(ProductsettlementActivity.this).inflate(R.layout.item_delivery, null);

                deliverygoodslist = bottomSheetView.findViewById(R.id.deliverygoodslist);
                TextView adddelivery = bottomSheetView.findViewById(R.id.adddelivery);

                adddelivery.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 添加新的收货地址的逻辑
                        Intent intent = new Intent(ProductsettlementActivity.this, AeliveryActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_DELIVERY);
                    }
                });
                bottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }
                });
                bottomSheetDialog.setContentView(bottomSheetView);

                // 初始化底部弹窗的数据
                sendAddressList(deliverygoodslist);
                bottomSheetDialog.show();

            }
        });
    }




    private void sendAddressList(RecyclerView deliverygoodslist) {
        OKHttpTool.doNetRequest("prod-api/api/takeout/address/list",
                OKHttpTool.GET,
                AddressList.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        AddressList alacarteBean = (AddressList) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                deliverygoodslist.setLayoutManager(new LinearLayoutManager(ProductsettlementActivity.this));
                                deliverygoodslist.setAdapter(new ShowAddressAdapter(ProductsettlementActivity.this, alacarteBean.getData()));
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }


    public void dismissDialog(String data) {
        Gson gson = new Gson();
        addressData = gson.fromJson(data, AddressList.DataBean.class);
        if (data != null) {
            delivery.setVisibility(View.GONE);
            readdressDetail.setVisibility(View.VISIBLE);
            address.setText(addressData.getAddressDetail());
            name.setText(addressData.getName());
            phone.setText(addressData.getPhone());

            createOrderObject();
        }
    }

    private void initView() {
        Intent intent = getIntent();
        money = intent.getStringExtra("money");
        gson = new Gson();
        String alacarteBean = intent.getStringExtra("alacarteBean");
        AlacarteBean dataBean = gson.fromJson(alacarteBean, AlacarteBean.class);

        list = new ArrayList<>();
        for (AlacarteBean.DataBean bean : dataBean.getData()) {
            if (bean.getCounter() > 0) {
                list.add(bean);
            }
        }



        back = findViewById(R.id.back);
        frame = findViewById(R.id.frame);
        delivery = findViewById(R.id.delivery);
        readdressDetail = findViewById(R.id.readdressDetail);
        address = findViewById(R.id.address);
        name = findViewById(R.id.name);
        phone = findViewById(R.id.phone);
        refoodlist = findViewById(R.id.refoodlist);
        submitorder = findViewById(R.id.submitorder);
        tv_money = findViewById(R.id.money);
        pay = findViewById(R.id.pay);

        tv_money.setText(money);

        delivery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddress("initial data");
            }
        });



        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProductsettlementActivity.this.finish();
            }
        });
    }
}